<template>
  <div class="content">
    <div class="top">
      <el-button size="small" type="primary" @click="onCreateClick"
        >新增员工角色</el-button
      >
      <el-button
        class="search"
        size="small"
        type="primary"
        @click="searchMember"
        >搜索</el-button
      >
      <el-input
        class="search input"
        size="small"
        v-model="query.keyword"
        placeholder="输入角色名称搜索"
        clearable
      ></el-input>
    </div>
      <el-table
        :data="tableData"
        style="width:100%"
        :cell-style="tc"
        :max-height="screenHight"
        :header-cell-style="tccolor"
        class="table"
      >
        <el-table-column label="角色ID" prop="id"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <!-- <el-table-column
          label="已绑定员工数"
          prop="account_num"
        ></el-table-column> -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <span class="light" @click="onDetailClick(scope.row)">详情</span>
            <span class="light" @click="onRemoveClick(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    <el-col :span="24">
      <div class="pagination">
        <el-pagination
          background
          @current-change="pageChange"
          :current-page="query.pageNum"
          :page-size="query.pageSize"
          :page-sizes="[20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-col>
    <jdialog
      :title="dialogType === 0 ? '新增角色' : '角色详情'"
      :visible.sync="dialogShow"
      :isComponent=1
      @handleCancel="handleCancel"
      width="800px"
    >
      <el-form
        :model="formDataAdd"
        :rules="rules"
        label-position="left"
        v-loading="dialogLoading"
        class="form-box"
      >
        <p class="title-line">
          {{ dialogType === 0 ? '新增角色名称' : '角色名称' }}
        </p>
        <div  class="border-box" >
          <el-form-item prop="name">
            <el-input
              v-model="formDataAdd.roleName"
              placeholder="请输入员工角色"
              maxlength="16"
              show-word-limit
            ></el-input>
            <p class="title-line">
              创建角色成功后，在新增员工关联该角色时自动获得权限
            </p>
          </el-form-item>
          <el-form-item prop="roleKey">
            <el-input
              v-model="formDataAdd.roleKey"
              placeholder="权限字符"
              maxlength="16"
              show-word-limit
            ></el-input>
            <p class="title-line">
              此字段必填
            </p>
          </el-form-item>
        </div>
        
        <p class="title-line">菜单查看权限</p>
        <div class="border-box">
          <el-tree
            :data="menuData"
            class="menu"
            show-checkbox
            default-expand-all
            :default-checked-keys="[1, 5, 503]"
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            check-strictly
          >
          </el-tree>
        </div>
        <div class="btns">
          <el-button class="btn" type="primary" @click="onComfirmClick"
            >确定</el-button
          >
          <el-button class="btn" type="info" @click="onCancelClick"
            >取消</el-button
          >
        </div>
      </el-form>
    </jdialog>
  </div>
</template>

<script>
import {
  getMemberPermissionMenu,
  getMemberRoleList,
  getMemberRoleInfo,
  roleDelete,
  roleUpdate,
  deleteMemberRole,
  getRole,
  getListMenuNode,
  roleCreate,
  roleList,
  roleDetails
} from '@/api/member'
import { findMatchPermissionItem } from '@/config/permission'
import { checkGranted } from '@/config/permission'
export default {
  data() {
    return {
      formDataAdd: {
        id: '',
        roleName: '',
        roleKey: '',
        roleSort: 0,
        dataScope: '',
        status: 0,
        remark: '',
        menuIds: []

      },
      form: {
        name: '',
        page: 1,
        size: 20
      },
      total: 0,
      tableData: [],
      dialogType: 0,
      dialogShow: false,
      // 记录操作角色的id
      tempId: 0,
      infoForm: { name: '' },
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      query:{
        pageNum:1,
        pageSize:10,
        partnerId:sessionStorage.getItem('partnerId'),
        keyword:''
      },
      menuData: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      dialogLoading: false
    }
  },
  created() {
    this.getMenuData()
    this.getRoleData()
  },
  methods: {
    getMenuData() {
      getListMenuNode(sessionStorage.getItem('LOGIN_USERNAME_id')).then(res => {
        if (res.code === 200) {
          const list = res.data || []
          console.log(list,'数据简报、账户信息')
          // 数据简报、账户信息
          // const obj1 = findMatchPermissionItem(item => item.id === 1, list)
          // obj1.disabled = true
          // const obj2 = findMatchPermissionItem(item => item.id === 5, list)
          // obj2.disabled = true
          // const obj3 = findMatchPermissionItem(item => item.id === 503, list)
          // obj3.disabled = true
          this.menuData = list
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getRoleData() {
      
      roleList(this.query).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list || []
          this.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 创建角色
    onCreateClick() {
      // const res = checkGranted(50201)
      // if (!res) {
      //   this.$message.error('对不起，您暂无该功能的权限')
      //   return
      // }
      this.infoForm.name = ''
      this.$refs.tree.setCheckedKeys([])
      this.dialogLoading = false
      this.dialogType = 0
      this.dialogShow = true
    },
    searchMember() {
      this.getRoleData()
    },
    pageChange(page) {
      this.query.pageNum = page
      this.getData()
    },
    onDetailClick(item) {
      this.dialogLoading = true
      this.dialogType = 1
      this.dialogShow = true
      this.tempId = item.id
      roleDetails(item.id).then(res => {
        if (res.code === 200) {
          this.dialogLoading = false
          this.formDataAdd = res.data
          //设置tree选中的项
          const menu = res.data.menuIds

          this.setSelectDataInTree(menu)
        } else {
          this.dialogLoading = false
          this.dialogShow = false
          this.$message.error(res.message)
        }
      })
    },
    setSelectDataInTree(menu) {
      // this.$refs.tree.setCheckedNodes(this.getChildNode(menu))
      this.$refs.tree.setCheckedKeys(menu);
    },
    getChildNode(node) {
      const array = []
      if (!node || node.length === 0) {
        return array
      }

      for (let n of node) {
        if (n.is_bind) {
          array.push({
            id: n.id,
            name: n.name
          })
        }
        if (n.child && n.child.length !== 0) {
          Array.prototype.push.apply(array, this.getChildNode(n.child))
        }
      }
      return array
    },
    onRemoveClick(item) {
      const res = checkGranted(50202)
      if (!res) {
        this.$message.error('对不起，您暂无该功能的权限')
        return
      }
      this.$confirm('确定删除该角色吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //删除角色
        roleDelete(item.id).then(res => {
          if (res.code === 200) {
            this.$message.success('成功删除')
            this.getRoleData()
          } else {
            this.$message.error(res.message)
          }
        })
      })
    },
    onComfirmClick() {
      if(!this.formDataAdd.roleName){
        this.$message.error('请输入角色名称')
        return
      }
      if(!this.formDataAdd.roleKey){
        this.$message.error('请输入权限字符')
        return
      }
      const array = this.$refs.tree.getCheckedKeys()
      console.log(array)
      this.formDataAdd.menuIds = array
      this.dialogLoading = true
      if (this.dialogType === 0) {
        // 确认创建
        roleCreate(
          Object.assign(this.formDataAdd)
        ).then(res => {
          if (res.code === 200) {
            this.$message.success('创建成功')
            this.$refs.tree.setCheckedKeys([])
            this.dialogLoading = false
            this.dialogShow = false
            this.infoForm.name = ''
            this.query.pageNum = 1
            this.getRoleData()
          } else {
            this.dialogLoading = false
            this.$message.error(res.message)
            this.dialogLoading = false
          }
        })
      } else {
        roleUpdate(
          this.formDataAdd
        ).then(res => {
          if (res.code === 200) {
            this.$message.success('编辑成功')
            this.$refs.tree.setCheckedKeys([])
            this.dialogLoading = false
            this.dialogShow = false
            this.infoForm.name = ''
            this.getRoleData()
          } else {
            this.dialogLoading = false
            this.$message.error(res.message)
          }
        })
      }
    },
    handleCancel(){
      // console.log(e)
      this.onCancelClick()
    },
    onCancelClick() {
      this.dialogShow = false
      this.formDataAdd= {
        id: '',
        roleName: '',
        roleKey: '',
        roleSort: 0,
        dataScope: '',
        status: 0,
        remark: '',
        menuIds: []

      }
    },
    tc() {
      return 'text-align:center; color:#333333; font-size:12px;'
    },
    tccolor() {
      return 'text-align:center;background-color:#f5f5f5; font-size:14px;'
    }
  }
}
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  background-color: #fff;
  height: 100%;
  padding: 10px 20px 0 ;
  box-sizing: border-box;
  .top {
    margin-bottom: 20px;
    .search {
      float: right;
      margin-left: 12px;
    }
    .input {
      width: 180px;
    }
  }
  .table {
    height: calc(100vh - 220px);
    .light {
      cursor: pointer;
      color: blue;
      &:first-child {
        margin-right: 12px;
      }
    }
  }
  .pagination {
    position: absolute;
    bottom: 10px;
    right: 20px;
    z-index: 99;
  }
  .form-box {
    padding: 0 16px 16px;
    .title-line {
      height: 40px;
      line-height: 40px;
    }
    .border-box {
      padding: 8px 8px 0;
      border: 1px solid #999;
      .menu {
        max-height: 250px;
        overflow-y: scroll;
      }
    }
    .btns {
      margin-top: 12px;
      text-align: center;
      .btn:first-child {
        margin-right: 12px;
      }
    }
  }
}
</style>
